const JSONbig = require('json-bigint')({ storeAsString: true });

export default {
  deletePageByPath({ commit, state }, params) {
    const { openPages } = state;
    const { path } = params;
    const newOpenPages = [];
    openPages.forEach((item) => {
      if (item.path !== path) {
        newOpenPages.push(item);
      }
    });
    commit('setOpenPages', newOpenPages);
  },
  updateOpenPages({ commit, state }, params) {
    const { openPages } = state;
    const openPagesString = [];
    openPages.forEach((item) => { openPagesString.push(JSON.stringify(item)); });
    if (!openPagesString.includes(JSON.stringify(params))) {
      openPages.push(params);
      commit('setOpenPages', openPages);
    }
  },
  updateNaviData({ commit }, data) { // 控制选中的菜单项
    const { key } = data;
    if (key) {
      commit('setSelectedKeys', [key]);
    }
  },
  // eslint-disable-next-line
  fetchData ({ commit }, {
    method = 'GET', page = {}, router, condition = {},
  }) {
    const { _vm } = this;
    const option = { ...condition };
    let paramPage = '';
    if (JSON.stringify(page) !== '{}') {
      option.page = { current: page.current, size: (typeof page.size === 'undefined' ? global.config.pageSize : page.size) };
      paramPage = `${JSON.stringify(condition) !== '{}' ? '&' : ''}pageNum=${page.pageNum}&pageSize=${page.pageSize}`;
    }
    if (typeof router === 'string') {
      switch (method) {
        default:
        case 'GET':
          // eslint-disable-next-line no-case-declarations
          let params = '';
          Object.keys(condition).forEach((item, key) => {
            params += `${key === 0 ? '' : '&'}${item}=${condition[item]}`;
          });
          return new Promise((resolve, reject) => {
            _vm.$axios.get(`${global.config.domain}${router}${(params || paramPage) ? '?' : ''}${params}${paramPage}`).then((res) => { if (typeof res !== 'undefined') { resolve(res); } }).catch((e) => { reject(e); });
          });
        case 'POST':
          // 解决精度丢失的bug --- 默认把bigint 转换成字符串
          return new Promise((resolve, reject) => {
            _vm.$axios.post(`${global.config.domain}${router}`, option, {
              transformResponse: [(data) => {
                if (typeof data === 'string') {
                  try {
                    data = JSONbig.parse(data);
                  } catch (e) { /* Ignore */ }
                }
                return data;
              }],
            }).then((res) => { if (typeof res !== 'undefined') { resolve(res); } }).catch((e) => { reject(e); });
          });
      }
    }
  },
};
